'''
Created on Apr 20, 2010

@author: darkelf
'''
import xml.dom.minidom
from basic.danzar_objects import *
#from basic.html_objects import *
from xml.dom.minidom import Node
from string import whitespace
import string
import os

class DMLParser:
    
    def __init__(self):
        self.html_page = None
        self.path_to_main_dml = ''
    
    def parse_dml_file(self, dml_path):
        self.path_to_main_dml = dml_path        
        dml_file =  xml.dom.minidom.parse(dml_path) 
        
        dml_root = dml_file.documentElement       
        
        self.html_page = self.get_object(dml_root.nodeName)            
        self.construct_childs(dml_root,self.html_page)                                    
        
        return self.html_page
    
    def append_component(self, component_name):
        print "Appending " + component_name + " component..."
        component_path = os.path.dirname(self.path_to_main_dml)
        component_path = os.path.join(component_path, component_name+".dml")
        component_file = xml.dom.minidom.parse(component_path) 
        
        component_root = component_file.documentElement
        
        component_object = self.get_object(component_root.nodeName)
        self.construct_childs(component_root,component_object)
        
        return component_object        
        
    def construct_childs(self,parent, p_object):        
        for node in parent.childNodes:            
            if node.nodeType == Node.ELEMENT_NODE:
                object = self.get_object(node.nodeName)
                
                content = []
                for ch in node.childNodes:
                    if ch.nodeType == Node.TEXT_NODE:                        
                        st = str(ch.nodeValue).replace("\r", "")
                        st = st.replace("\n","")
                        st = st.replace("\t","")                        
                        if len(st) > 0:
                            content.append(ch.nodeValue)
                if content:
                    object.set_content(string.join(content))
                else:
                    self.construct_childs(node,object)                
                self.construct_attributes(object, node)
                object.detect_functions(p_object)
                p_object.childs.append(object)                
    
    def construct_attributes(self,object, node):
        attributes = node.attributes
        a = 0
        while a < attributes.length:
            item = attributes.item(a)            
            object.__getattribute__("set_"+item.name)(item.value)
            a+=1                    
    
    def get_object(self,object_name):
        if(globals().has_key(object_name)):
            _class = globals()[object_name]
            return _class()
        return self.append_component(object_name)         